﻿using Hazdryx.Drawing;
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;

namespace EmotionsExtract.UITex
{
    internal class ImageUtils
    {
        /// <summary>
        /// 使用 Pfim 加载 TGA/DDS 文件并转换为 Bitmap
        /// </summary>
        /// <param name="fileName">输入的 TGA/DDS 文件路径</param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public static FastBitmap LoadTexture(string fileName)
        {
            using (var image = Pfim.Pfim.FromFile(fileName))
            {
                PixelFormat format;
                switch (image.Format)
                {
                    case Pfim.ImageFormat.Rgba32:
                        format = PixelFormat.Format32bppArgb;
                        break;
                    case Pfim.ImageFormat.Rgb24:
                        format = PixelFormat.Format24bppRgb;
                        break;
                    default:
                        throw new NotImplementedException($"不支持的像素格式：{image.Format}");
                }

                GCHandle handle = GCHandle.Alloc(image.Data, GCHandleType.Pinned);
                Bitmap ptrBmp = new Bitmap(image.Width, image.Height, image.Stride, format, Marshal.UnsafeAddrOfPinnedArrayElement(image.Data, 0));
                FastBitmap ret = new FastBitmap(ptrBmp);
                ptrBmp.Dispose();
                handle.Free();
                return ret;
            }
        }

        /// <summary>
        /// 二值化透明通道
        /// </summary>
        /// <param name="source">源 Bitmap</param>
        /// <param name="thershold">二值化阈值，默认为 128 （50%），Alpha 值大于等于此值的像素将会被转换为不透明，反之转换为全透明</param>
        /// <returns></returns>
        public static Bitmap BinarizeTransparancy(Bitmap source, int thershold = 128)
        {
            Bitmap ret = (Bitmap)source.Clone();
            for (int x = 0; x < ret.Width; x++)
            for (int y = 0; y < ret.Height; y++)
            {
                Color oldColor = ret.GetPixel(x, y);
                Color newColor = Color.FromArgb(oldColor.A >= thershold ? 0xFF : 0x00, oldColor.R, oldColor.G, oldColor.B);
                ret.SetPixel(x, y, newColor);
            }
            return ret;
        }
    }
}
